package io.adrainty.bolee.framework.web.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.StrPool;
import io.adrainty.bolee.framework.commons.exception.CoreException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.BufferedReader;
import java.io.IOException;

/**
 * RequestContextHolder工具类
 * @author adrainty
 * @version v1.0.0
 * @since 2023/12/12 17:40
 */

@SuppressWarnings("unused")
public class RequestContextUtil {

    private RequestContextUtil() {
    }

    /**
     * 根路径
     */
    private static final String ROOT_PATH = "/";

    /**
     * cookie过期时间
     */
    private static final int COOKIE_EXPIRE_TIME = 60 * 60 * 12;

    /**
     * 多ip地址分隔符
     */
    private static final String MULTI_IP_SPLIT_SYMBOL = ",";

    /**
     * 获取请求对象
     * @return 请求对象
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取响应对象
     * @return 响应对象
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取请求方法
     * @return 请求方法
     */
    public static String getRequestMethod() {
        return getRequest().getMethod();
    }

    /**
     * 获取请求url
     * @return 请求url
     */
    public static String getRequestUrl() {
        return getRequest().getRequestURI();
    }

    /**
     * 获取请求参数
     * @return 请求参数
     */
    public static String getRequestParams() {
        return getRequest().getQueryString();
    }

    /**
     * 获取客户端ip地址
     * @return ip地址
     */
    public static String getRemoteIpAddr() {
        HttpServletRequest request = getRequest();
        String ip;
        String unknown = "unknown";
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isBlank(ip) || ip.isEmpty() || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            throw new CoreException(e);
        }
        if (StringUtils.isBlank(ip) && ip.contains(MULTI_IP_SPLIT_SYMBOL)) {
            ip = ip.substring(0, ip.indexOf(MULTI_IP_SPLIT_SYMBOL));
        }

        return ip;
    }

    public static String getRemoteHost(HttpServletRequest request) {
        if (request == null) request = getRequest();
        String host;
        try {
            host = request.getHeader("x-forwarded-host");
            if (StringUtils.isNotBlank(host)) {
                host = host.split(StrPool.COMMA)[0].split(StrPool.COLON)[0];
            }
            if (StringUtils.isBlank(host)) {
                host = request.getHeader("host");
            }
            if (StringUtils.isBlank(host)) {
                host = request.getRemoteHost();
            }
        } catch (Exception e) {
            throw new CoreException(e);
        }
        return host;
    }

    /**
     * 获取cookie
     * @param name cookie名称
     * @return cookie值
     */
    public static String getCookie(String name) {
        if (StringUtils.isBlank(name)) return StringUtils.EMPTY;
        Cookie[] cookies = getRequest().getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) return cookie.getValue();
            }
        }
        return StringUtils.EMPTY;
    }

    /**
     * 设置cookie
     * @param key key
     * @param value value
     */
    public static void setResponseCookie(String key, String value) {
        setResponseCookie(key, value, COOKIE_EXPIRE_TIME);
    }

    /**
     * 设置cookie
     * @param key key
     * @param value value
     * @param time time
     */
    public static void setResponseCookie(String key, String value, int time) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath(ROOT_PATH);
        cookie.setDomain(getRequest().getRequestURI());
        cookie.setMaxAge(time);
        HttpServletResponse response = getResponse();
        assert response != null;
        response.addCookie(cookie);
    }

    /**
     * 获取requestAttributes
     * @return requestAttributes
     */
    public static ServletRequestAttributes getRequestAttributes() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        return attributes;
    }

    /**
     * 读取请求数据
     * @return 请求数据
     */
    public static String readData() {
        HttpServletRequest request = getRequest();
        try (BufferedReader reader = request.getReader()) {
            return IoUtil.read(reader);
        } catch (IOException e) {
            throw new CoreException(e);
        }
    }
}
